package cn.eveo.refreshandloadmore.view;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

/**
 * 修改自com.jcodecraeer.xrecyclerview
 * <p/>
 * 仅添加加载更多功能
 */
public class ERecyclerView extends RecyclerView {

    protected interface LoadMoreListener {
        void onLoadMore();
    }

    /**
     * 加载项type，外部的type不能与该type相同
     **/
    private static final int TYPE_LOAD_MORE = Integer.MAX_VALUE;
    /**
     * 加载项数量
     **/
    private static final int LOADMORE_VIEW_COUNT = 1;
    /**
     * 能否加载更多
     **/
    private boolean loadMoreEnabled = false;

    private LoadMoreListener loadMoreListener;

    private LoadMoreView loadMoreView;
    private WrapAdapter mWrapAdapter;


    public ERecyclerView(Context context) {
        super(context);
        init();
    }

    public ERecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ERecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();

    }

    private void init() {
        loadMoreView = new LoadMoreView(getContext());
        loadMoreView.setLayoutParams(new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        loadMoreView.setState(LoadMoreView.STATE_NOT_ENABLED);
    }

    /**
     * 是否显示加载更多项
     **/
    protected void setLoadingMoreEnabled(boolean enabled) {
        loadMoreEnabled = enabled;
    }

    /**
     * 监听加载
     **/
    protected void setLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }

    protected void dismissLoadMoreView() {
        if (null != loadMoreView) {
            loadMoreView.setState(LoadMoreView.STATE_NOT_ENABLED);
        }
    }

    /**
     * 加载完成
     **/
    protected void loadMoreComplete() {
        if (null == loadMoreView || !loadMoreEnabled || null == mWrapAdapter) {
            return;
        }
        if (mWrapAdapter.getItemCount() - LOADMORE_VIEW_COUNT <= 0) {
            loadMoreView.setState(LoadMoreView.STATE_NOT_ENABLED);
        } else {
            loadMoreView.setState(LoadMoreView.STATE_COMPLETE);
        }
    }

    /**
     * 无更多数据
     **/
    protected void noMore() {
        if (null == loadMoreView || !loadMoreEnabled) {
            return;
        }
        loadMoreView.setState(LoadMoreView.STATE_NOMORE);
    }

    /**
     * 覆盖父类方法，对使用者的adapter进行封装
     **/
    @Override
    public void setAdapter(Adapter adapter) {
        mWrapAdapter = new WrapAdapter(adapter);
        super.setAdapter(mWrapAdapter);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);

        if (state == RecyclerView.SCROLL_STATE_IDLE && loadMoreEnabled
                && mWrapAdapter.getItemCount() - LOADMORE_VIEW_COUNT > 0) {

            loadMoreView.setState(LoadMoreView.STATE_LOADING);
            if (loadMoreListener != null && !canScrollVertically(1)) {
                loadMoreListener.onLoadMore();
            }
        }
    }


    private class WrapAdapter extends Adapter<ViewHolder> {
        private Adapter adapter;

        public WrapAdapter(Adapter adapter) {
            this.adapter = adapter;
        }

        public boolean isFooter(int position) {
            return position == getItemCount() - LOADMORE_VIEW_COUNT;
        }

        /**
         * 实际count=外部adapter的count+加载更多项
         **/
        @Override
        public int getItemCount() {
            if (adapter != null) {
                if (0 == adapter.getItemCount() && null != loadMoreView) {
                    loadMoreView.setState(LoadMoreView.STATE_NOT_ENABLED);
                }

                return adapter.getItemCount() + LOADMORE_VIEW_COUNT;
            } else {
                return 0;
            }
        }

        /**
         * 实际type,先判断是否加载更多项，
         * 为否即取外部adapter的类型
         **/
        @Override
        public int getItemViewType(int position) {
            if (isFooter(position)) {
                return TYPE_LOAD_MORE;
            }
            if (adapter != null) {
                int adapterCount = adapter.getItemCount();
                if (position < adapterCount) {//先判断一下position有没有比外部adpter的count还要大
                    return adapter.getItemViewType(position);
                }
            }
            return 0;
        }

        /**
         * 实际创建的时候，先判断是否加载更多项，
         * 为否即取外部adapter的viewHolder
         **/
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_LOAD_MORE) {
                return new LoadMoreViewHolder(loadMoreView);
            }
            return adapter.onCreateViewHolder(parent, viewType);
        }

        /**
         * 实际绑定数据的时候，先判断是否加载更多项，
         * 为否即取外部adapter的bindViewHolder
         **/
        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            if (isFooter(position)) {
                return;
            }

            if (adapter != null) {
                int adapterCount = adapter.getItemCount();
                if (position < adapterCount) {
                    adapter.onBindViewHolder(holder, position);
                    return;
                }
            }
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);

            adapter.onAttachedToRecyclerView(recyclerView);
        }

        @Override
        public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
            adapter.onDetachedFromRecyclerView(recyclerView);
        }

        @Override
        public void onViewAttachedToWindow(ViewHolder holder) {
            super.onViewAttachedToWindow(holder);

            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if (lp != null
                    && lp instanceof StaggeredGridLayoutManager.LayoutParams
                    && (isFooter(holder.getLayoutPosition()))) {
                StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
                p.setFullSpan(true);
            }

            LayoutManager manager = getLayoutManager();
            if (manager instanceof GridLayoutManager) {
                final GridLayoutManager gridManager = ((GridLayoutManager) manager);
                gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return (isFooter(position))
                                ? gridManager.getSpanCount() : 1;
                    }
                });
            }

            adapter.onViewAttachedToWindow(holder);
        }

        @Override
        public void onViewDetachedFromWindow(ViewHolder holder) {
            adapter.onViewDetachedFromWindow(holder);
        }

        @Override
        public void onViewRecycled(ViewHolder holder) {
            adapter.onViewRecycled(holder);
        }

        @Override
        public boolean onFailedToRecycleView(ViewHolder holder) {
            return adapter.onFailedToRecycleView(holder);
        }

        @Override
        public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
            adapter.unregisterAdapterDataObserver(observer);
        }

        @Override
        public void registerAdapterDataObserver(AdapterDataObserver observer) {
            adapter.registerAdapterDataObserver(observer);
        }

        private class LoadMoreViewHolder extends ViewHolder {
            public LoadMoreViewHolder(View itemView) {
                super(itemView);
            }
        }
    }
}
